package com.xd.Filter;

import com.xd.Util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String authorizationHeader = request.getHeader("Authorization");

        if (request.getServletPath().startsWith("/admin/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        if(request.getServletPath().startsWith("/admin/common/upload")){
            filterChain.doFilter(request, response);
            return;
        }
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            // 设置HTTP状态码为401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // 使用Writer向响应体中写入错误信息
            PrintWriter writer = response.getWriter();
            writer.write("{\"error\": \"Unauthorized: Missing or invalid Authorization header\"}");
            writer.flush();
            writer.close();
            return;
        }

        String jwt = authorizationHeader.substring(7);
        try {
            String username = jwtUtil.getUsernameFromToken(jwt);
            // 设置用户认证信息等操作
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter writer = response.getWriter();
            writer.write("{\"error\": \"Invalid token\"}");
            writer.flush();
            writer.close();
            return; // 停止过滤器链
        }

        filterChain.doFilter(request, response);
    }
}

